package com.example.ebeanbase.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author huangke
 */
public class CommonFunctionUtil {

	/**
	 * @param str
	 *            需要加密的字符串
	 * @return
	 */
	public static String encryptionPwd(String str) {

		return string32MD5(str);
	}

	/***
	 * MD5加码 生成32位md5码
	 */
	public static String string32MD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for(int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();

	}

	/**
	 * 将date类型转为string
	 *
	 * @param time
	 * @param formatType
	 * @return
	 */
	public static String changeTimeString(Date time, String formatType) {

		SimpleDateFormat formatter = new SimpleDateFormat(formatType);

		return formatter.format(time);
	}

	/**
	 * 将string类型转为date
	 *
	 * @param time
	 * @param formatType
	 * @return
	 */
	public static Date changeTimeDate(String time, String formatType) throws ParseException {

		SimpleDateFormat formatter = new SimpleDateFormat(formatType);

		return formatter.parse(time);
	}

	/**
	 * 获取当前时间，返回string类型
	 *
	 * @param formatType
	 * @return
	 * @throws ParseException
	 */
	public static String getStringTime(String formatType) {

		SimpleDateFormat formatter = new SimpleDateFormat(formatType);

		return formatter.format(new Date());
	}

	/**
	 * 获取当前时间，返回date类型
	 *
	 * @param formatType
	 * @return
	 * @throws ParseException
	 */
	public static Date getDateTime(String formatType) throws ParseException {

		SimpleDateFormat formatter = new SimpleDateFormat(formatType);

		return formatter.parse(formatter.format(new Date()));
	}

	/**
	 * 生成uuid
	 *
	 * @return
	 */
	public static String createUuid() {

		return UUID.randomUUID().toString().replace("-", "").toLowerCase();
	}

	/**
	 * 随机验证码
	 *
	 * @return
	 */
	public static String random() {

		int result = (int) ((Math.random() * 9 + 1) * 100000);

		return String.valueOf(result);
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @Description: 获取客户端IP地址
	 */
	public static String getClientIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (Exception e) {
					e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}
		// 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}

}
